package com.baofu.trade.config;

import lombok.extern.slf4j.Slf4j;
import org.knowm.xchange.Exchange;
import org.knowm.xchange.ExchangeFactory;
import org.knowm.xchange.ExchangeSpecification;
import org.knowm.xchange.binance.BinanceExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.EnableRetry;
import org.springframework.retry.annotation.Retryable;

import java.net.InetSocketAddress;
import java.net.Proxy;

@Slf4j
@Configuration
@EnableRetry
public class BinanceConfig {
    
    @Bean
    @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000))
    public Exchange binanceExchange() {
        try {
            ExchangeSpecification spec = new ExchangeSpecification(BinanceExchange.class);
            
            // 设置超时时间（毫秒）
            spec.setHttpReadTimeout(60000);  // 读取超时：60秒
            spec.setHttpConnTimeout(30000);  // 连接超时：30秒
            
            // 设置请求限制
            spec.setExchangeSpecificParametersItem("rateLimit", 1000); // 降低请求频率
            
            // 配置代理设置
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 7890));
            spec.setProxyHost("127.0.0.1");
            spec.setProxyPort(7890);
            
            // 设置API基础URL（使用备用URL）
            spec.setExchangeSpecificParametersItem("Binance_REST_API", "https://api1.binance.com");
            
            // 禁用远程初始化，避免启动时的网络请求
            spec.setShouldLoadRemoteMetaData(false);
            
            log.info("正在创建币安交易所连接...");
            Exchange exchange = ExchangeFactory.INSTANCE.createExchange(spec);
            log.info("币安交易所连接创建成功");
            
            return exchange;
            
        } catch (Exception e) {
            log.error("创建币安交易所连接失败: {}", e.getMessage());
            // 创建一个基本的Exchange实例，避免应用启动失败
            ExchangeSpecification spec = new ExchangeSpecification(BinanceExchange.class);
            spec.setShouldLoadRemoteMetaData(false);
            return ExchangeFactory.INSTANCE.createExchange(spec);
        }
    }
} 